package httpServer;

import java.io.*;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by ab on 2016/11/1.
 */


public class Main implements Runnable {

    private Map Request;//http request header
    private Socket socket;
    private OutputStream out;
    private String response = "";
    private String staticFile;

    Main(Socket socket) {
        this.socket = socket;
        this.Request = new HashMap();
    }

    public String getStaticFile() {
        return staticFile;
    }

    public void setStaticFile(String staticFile) {
        this.staticFile = staticFile;
    }

    public OutputStream getOutput() throws IOException {
        return this.socket.getOutputStream();
    }

    private void Route() throws IOException {
        Pattern p = Pattern.compile("(.*\\..*)$");
        File file;
        String fileName= URLDecoder.decode(Request.get("route").toString(),"utf8");
        if (p.matcher(fileName).matches())
            file = new File(getStaticFile() + fileName);
        else
            file = new File(getStaticFile() + fileName + "\\index.html");


        if (file.isFile() && file.exists()) { //判断文件是否存在
            response = "HTTP/1.1 200 ok\r\n" +
                    "Content-Type: " + Files.probeContentType(file.toPath()) + "\r\n" +
                    "Content-Length : " + file.length() + "\r\n" +
                    "Server: Deep Dark Fantasy\r\n" +
                    "Date: " + new Date() + "\r\n\r\n";

            out.write(response.getBytes());
            int BUFFER_SIZE = 1024;
            byte[] bytes = new byte[BUFFER_SIZE];
            FileInputStream fis = new FileInputStream(file);
            int ch = fis.read(bytes, 0, BUFFER_SIZE);
            while (ch != -1) {
                out.write(bytes, 0, ch);
                ch = fis.read(bytes, 0, BUFFER_SIZE);
            }
        } else {
            response = "HTTP/1.1 404 not found\r\n" +
                    "Server: Deep Dark Fantasy\r\n" +
                    "Date: " + new Date() + "\r\n\r\n";

            out.write(response.getBytes());
        }

        System.out.println("[" + new Date() + "] " + Request.get("method") + " - " + fileName);

        out.flush();
        out.close();
        socket.close();
    }

    public void send(String content) throws IOException {
        String Header = "HTTP/1.1 200 ok\r\n" +
                "Content-Type: text/html\r\n" +
                "Server: Deep Dark Fantasy\r\n" +
                "Date: " + new Date() + "\r\n\r\n";
        out.write(response.getBytes());
        String html = content;
        out.write(html.getBytes());
    }


    public BufferedReader getBuffer() throws IOException {
        return new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }


    public void HttpRequest() throws IOException {
        BufferedReader bd = getBuffer();
        String requestHeader;
        if ((requestHeader = bd.readLine()) != null && !requestHeader.isEmpty()) {
            Request.put("method", requestHeader.split(" ")[0]);
            Request.put("route", requestHeader.split(" ")[1]);
        }
        while ((requestHeader = bd.readLine()) != null && !requestHeader.isEmpty()) {

        }
    }


    @Override
    public void run() {
        try {
            HttpRequest();
            out = getOutput();
            Route();


        } catch (Exception err) {
            System.err.println("[" + new Date() + "]" + err);
        }
    }
}